package javaIo;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.Future;

/**
 * Created by zzy on 2018/4/2.
 */
public class Aio {

    public static void main(String[] args) throws IOException, InterruptedException {
        final ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
        AsynchronousServerSocketChannel  server=AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(12345));
        //接收不阻塞，真正接受后执行回掉函数
        server.accept("123", new CompletionHandler<AsynchronousSocketChannel, String>() {
            @Override
            public void completed(AsynchronousSocketChannel result, String attachment) {
                Future<Integer> read=null;
                try {
                    byteBuffer.clear();
                    result.read(byteBuffer, "123", new CompletionHandler<Integer, String>() {
                        @Override
                        public void completed(Integer result, String attachment) {
                            try {
                                System.out.println(new String(byteBuffer.array(),"GBK"));
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                            System.out.println(result+attachment);
                        }

                        @Override
                        public void failed(Throwable exc, String attachment) {

                        }
                });


                }catch (Exception e){

                }finally {
                    server.accept(null,this);
                    try {
                        result.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("completed");
            }

            @Override
            public void failed(Throwable exc, String attachment) {
               System.out.println("failed");
            }
        });

        Thread.sleep(50000);
    }
}
